/*
 * @Author: xfworld
 * @Date: 2020-06-03 14:34:43
 * @LastEditors: xfworld
 * @LastEditTime: 2020-06-10 15:18:51
 * @Description:
 */

import store from "@/store";
import config from "@/config";
import {setToken, getToken, canTurnTo} from "@/libs/util";
const {homeName} = config;
const LOGIN_PAGE_NAME = "login";
const ERROR_401 = "AccessDenied";

const turnTo = (to, access, next) => {
  if (access != null && access.length > 0) {
    if (canTurnTo(to.name, access, routes)) {
      // 有权限，可访问
      next();
    } else {
      next({
        replace: true,
        name: ERROR_401
      }); // 无权限，重定向到401页面
    }
  } else {
    next({
      replace: true,
      name: ERROR_401
    });
  }
};

export default (to, from, next) => {
  // store.dispatch("app/setLoadingStatus", true);
  const token = getToken();
  if (token == "" && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    });
  } else if (token == "" && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next(); // 跳转
  } else if (token != "" && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    });
  } else if (token != "" && to.name === homeName) {
    next();
  } else if (token != "" && to.name === ERROR_401) {
    next();
  } else if (to.meta.access == null || to.meta.access == undefined) {
    next();
  } else {
    if (store.state.user.hasGetInfo) {
      if (store.state.user.adminStatus) {
        next();
      } else {
        turnTo(to, store.state.user.access, next);
      }
    } else {
      store
        .dispatch("getUserAccess")
        .then(user => {
          // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
          if (store.state.user.adminStatus) {
            next();
          } else {
            turnTo(to, user, next);
          }
        })
        .catch(() => {
          setToken("");
          next({
            name: "login"
          });
        });
    }
  }
};
